<?php 
class CCart extends Zend_Db_Table
{
	protected $_name;
	protected $_primary;
	public function __construct()
	{
		$this->_name=R_PRE. "cart";
		parent::__construct();
	}
	
	public function getCartStr($sessionId)
	{
		$rand = mt_rand(0,100);
		if ($rand % 10 == 0) {
			$this->_gc();
		}
		
		if (!$this->_exists($sessionId)) {
			return '';
		}
		
		$row = $this->fetchRow(array('cart_session_id = ?'=>$sessionId));
		if ($row->uid > 0) { //登录用户的cart,reset hash
			return '';
		}
		
		return $row->cart_str;		
	}
	
	public function getCartStrByUid($uid)
	{
		$rand = mt_rand(0,100);
		if ($rand % 10 == 0) {
			$this->_gc();
		}
		
//		if (!$this->_existsByUid($uid)) {
//			return '';
//		}
		
		$row = $this->fetchRow(array('uid = ?'=>$uid));	
		if (!$row) {
			if (!empty($_COOKIE[COOKIE_PRE.'product_buy_session'])) {
				$row = $this->fetchRow(array('cart_session_id = ?'=>$_COOKIE[COOKIE_PRE.'product_buy_session']));
				if ($row) {
					$this->update(array('uid'=>$uid), 'cart_session_id = "' . addslashes($_COOKIE[COOKIE_PRE.'product_buy_session']) . '"');
				}
			}
		}	
		if (!$row) {
			return '';
		}
		if ($row->expires > time()) {			
			return $row->cart_str;
		} else {
			$this->delete('uid = ' . intval($uid));
			return '';
		}
	}
	
	public function setCartStr($sessionId, $row)
	{
		$db = $this->getAdapter();
		$where = $db->quoteInto('cart_session_id = ?', $sessionId);
		if ($this->_exists($sessionId)) {
			return $this->update($row, $where);	
		} else {
			$row['cart_session_id'] = $sessionId;
			return $this->insert($row);
		}
	}
	
	public function setCartStrByUid($uid, $row)
	{
		$db = $this->getAdapter();
		$where = $db->quoteInto('uid = ?', $uid);
		$where .= ' and expires > ' . time();
		if ($this->_existsByUid($uid)) {
			return $this->update($row, $where);	
		} else {
			if ($this->_exists($row['cart_session_id'])) {
				$row['uid'] = $uid;
				return $this->update($row, 'cart_session_id = "' . addslashes($row['cart_session_id']) . '"');
			}			
			return $this->insert($row);
		}
	}
	
	protected function _exists($sessionId)
	{
		if (empty($sessionId)) {
			return '';
		}
		$rowSet = $this->fetchAll(array('cart_session_id = ?'=>$sessionId));
		if (count($rowSet) > 0) {
			return true;
		}
		return false;
	}
	
	protected function _existsByUid($uid)
	{
		$rowSet = $this->fetchAll(array('uid = ?'=>$uid));
		if (count($rowSet) > 0) {
			if ($rowSet->expires > time()) {
				return true;
			} else {
				$this->delete('uid = ' . intval($uid));
				return false;
			}
		}
		return false;
	}
	
	protected function _gc()
	{
		$db = $this->getAdapter();
		$db->query('delete from ' . $this->_name . ' where expires < ' . time());
	}
	
	public function sessionHash()
	{
		return md5(session_id() . time());
	}
	
}